/**
 * Copyright (c) 2018 苍穹跃龙
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.l.web.login.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.l.core.constant.UserStatus;
import com.l.core.util.WebUtils;
import com.l.core.web.RestCode;
import com.l.core.web.RestJson;
import com.l.web.login.entity.Login;
import com.l.web.master.system.entity.SysUser;
import com.l.web.master.system.service.ISysUserService;

/**
 * <p>
 * Copyright: Copyright (c) 2018
 * </p>
 * 
 * @author 严秋旺
 * @date 2018-09-20
 */
@Controller
public class LoginController {
    @Autowired
    private ISysUserService userService;

    @RequestMapping({ "/", "login" })
    public String index(Model model) {
        return "login";
    }

    @RequestMapping("doLogin")
    @ResponseBody
    public RestJson index(@Valid Login login, Errors errors) {
        if (errors.hasErrors()) {
            return new RestJson(RestCode.FORM_BAD, errors);
        }

        SysUser user = userService.findUserByUserName(login.getUserName());

        if (user == null) {
            return new RestJson(RestCode.LOGIN_USERNAME_OR_PASSWORD_ERROR);
        }

        String password = user.getPassword();
        user.setPassword(login.getPassword());
        String encryptPassword = userService.encryptPassword(user);

        if (!encryptPassword.equals(password)) {
            return new RestJson(RestCode.LOGIN_USERNAME_OR_PASSWORD_ERROR);
        }

        if (UserStatus.ENABLED != user.getStatus()) {
            return new RestJson(RestCode.LOGIN_USER_LOCKED);
        }

        WebUtils.setLogin(user);
        return RestJson.Success();
    }

    @RequestMapping("logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath());
    }
}
